// pages/phonebook/phonebook.js
import request from '../../utils/request'

Page({
  data: {
    contacts: [],
    filteredContacts: [],
    searchText: '',
    loading: true,
    departmentColors: {
      '产品经理': '#4A90E2',
      '产品部': '#7BAAF7',
      '设计部': '#FF9500',
      '市场部': '#34C759',
      '人力资源': '#FF2D55',
      '运营部': '#AF52DE',
      '财务部': '#5856D6'
    },
    departmentMap: {
      104: '技术部',
      105: '产品部',
      106: '设计部'
 
    },
    statusMap: {
      'formal': '正式',
      'probation': '试用',
      'leave': '离职',
      'retired': '退休'
    }
  },

  onLoad() {
    this.fetchContactList()
  },

  // 获取通讯录列表
  async fetchContactList() {
    try {
      this.setData({ loading: true })
      
      const res = await request.get('/zdtj/zdtj/list')
      
      if (res.code === 200) {
        this.setData({
          contacts: this.formatContactData(res.rows),
          filteredContacts: this.formatContactData(res.rows),
          loading: false
        })
      } else {
        wx.showToast({
          title: res.msg || '获取通讯录失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('获取通讯录失败:', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 格式化联系人数据
  formatContactData(data) {
    return data.map(item => ({
      id: item.id,
      avatar: item.avatar || '/images/default-avatar.png', // 默认头像
      name: item.name || '未命名',
      department: this.data.departmentMap[item.departmentId] || '未分配部门',
      position: item.positionName || '暂无职位',
      phone: item.phone || '暂无号码',
      hireDate: item.hireDate ? this.formatDate(item.hireDate) : '未填写',
      employee:item.employee ||'暂无工号'
    }))
  },

  // 格式化日期
  formatDate(dateStr) {
    const date = new Date(dateStr)
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
  },

  // 搜索功能
  handleSearchInput(e) {
    const searchText = (e.detail.value || '').toLowerCase().trim();
    
    this.setData({
      filteredContacts: this.data.contacts.filter(item => {
        // 安全获取所有可能搜索的字段，并提供默认值
        const searchableFields = [
          item.name || '',
          item.department || '',
          item.position || '',
          item.employeeNumber || '',
          item.phone || ''
        ];
        
        // 检查是否有字段匹配搜索文本
        return searchableFields.some(
          field => field.toLowerCase().includes(searchText)
        );
      })
    });
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchText: '',
      filteredContacts: this.data.contacts
    })
  },

  // 拨打电话
  makePhoneCall(e) {
    const phone = e.currentTarget.dataset.phone
    if (!phone || phone === '暂无号码') {
      wx.showToast({
        title: '该联系人暂无电话号码',
        icon: 'none'
      })
      return
    }
    
    wx.makePhoneCall({
      phoneNumber: phone,
      success: () => console.log('拨号成功'),
      fail: (err) => {
        console.error('拨号失败:', err)
        wx.showToast({
          title: '拨号失败',
          icon: 'none'
        })
      }
    })
  },

  // 查看详情
  viewDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/contactDetail/contactDetail?id=${id}`
    })
  }
})